import React, { Component } from 'react';
import { StyleSheet, Text, View, Dimensions, Platform, ScrollView, TouchableOpacity, Image, TextInput, Alert } from "react-native";
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import Dictionary from '../../../utils/dictionary';
import { CheckBoxCpt } from './_components/form/CheckBoxCpt';
import { RadoiCpt } from './_components/form/RadoiCpt';
import OfferCreateMethods from './OfferCreateMethods';
const checkOn = require('../../../imgs/order/select-on.png');
const checkOff = require('../../../imgs/order/select-off.png');
const ScreenWidth = Dimensions.get('window').width;
const scale = ScreenWidth / 375;
const searchIcon = require('../../../imgs/global/whiteSearch.png');

export class TargetCustomers extends Component {
	static navigationOptions = ({ navigation }) => {
		const params = navigation.state.params || {};
		return {
			headerTitle: '定向客户',
			headerTintColor: style.color.white,//
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color="#fff" />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: style.head.headerTitleStyle
		}
	};

	constructor(props) {
		super(props);
		let { salesType, goodsCateIds, salePurchaseAreaId, targetData, readOnly, bidPackageApplyId } = props.navigation.state.params || {};
		let { channel, resourceGroupIds, companyTypeIds, areaIds } = targetData
		this.state = {
			channel: channel || '1',

			dataList: [
			],
			readOnly: readOnly || false
		}
		this.EnterpriseChannel = [
			{
				dictName: '按群组选择',
				dictKey: '1'
			},
			{
				dictName: '按类型选择',
				dictKey: '2'
			}
		]
		this.salesArea = []
		this.companyProp = [],
			this.pageParams = {
				salesType
			}
		this.groupParams = {
			channel: '1',
			channelName: '已按群组选择',
			salesType,
			goodsCateIds,
			salePurchaseAreaId,
			resourceGroupIds: resourceGroupIds || [],
			bidPackageApplyId,
		}
		this.typeParams = {
			salesType,
			goodsCateIds,
			salePurchaseAreaId,
			companyTypes: companyTypeIds || [],
			areaIds: areaIds || [],
			channel: '2',
			channelName: '已按类型选择',
			bidPackageApplyId,
		}
		this.salePurchaseAreaId = salePurchaseAreaId
	}

	componentWillMount() {
		this._init();
	}
	_init = async () => {
		let salesArr = await OfferCreateMethods.getDict('EC_PRICE_REGION');
		for (var i in salesArr) {
			this.salesArea.push({
				dictKey: salesArr[i].dictKey,
				dictName: salesArr[i].dictName
			});
		}
		if (this.salePurchaseAreaId !== 'F') {
			this.salesArea.map(item => {
				if (item.dictKey === this.salePurchaseAreaId) {
					item.readOnly = false
				}
				else if (item.dictKey === 'F') {
					item.readOnly = false
				}
				else {
					item.readOnly = true
				}
			})
		}
		else {
			this.salesArea.map(item => {
				item.readOnly = false
			})
		}
		let companyProp = await Dictionary.get('COMPANY_PROP');
		console.log(companyProp)
		for (var i in companyProp) {
			this.companyProp.push({
				dictKey: companyProp[i].dictKey,
				dictName: companyProp[i].dictName
			});
		}
		await this.initPage()
		if (this.state.readOnly) {
			await this.readOnly()
		}
	}
	initPage = async () => {
		this.setState({
			status: 'loading'
		})
		this.pageParams.searchKey = this.searchKey
		let { resourceGroupIds } = this.groupParams
		if (this.state.readOnly) {
			this.pageParams.resourceGroupIds = resourceGroupIds
		}
		let res = await HTTP.POST(API_GENERATE(API.TARGET_GROUP), this.pageParams);
		if (res) {
			if (resourceGroupIds.length > 0) {
				res.map(item => {
					let arr = resourceGroupIds.filter(_item => _item === item.resourceGroupId)
					if (arr.length > 0) {
						item.checked = true
					}
				})
			}
			this.setState({
				dataList: res,
				status: res.length > 0 ? 'data' : 'empty'
			})
		}
		else {
			this.setState({
				status: 'error'
			})
		}

	}
	async readOnly() {
		if (this.state.channel == '1') {
			this.EnterpriseChannel = [
				{
					dictName: '按群组选择',
					dictKey: '1'
				}
			]
		}
		else {
			this.EnterpriseChannel = [
				{
					dictName: '按类型选择',
					dictKey: '2'
				}
			]
		}
		let arrArea = [], arrCompany = []
		this.salesArea.map(item => {
			if (item.checked) {
				arrArea.push(item)
			}
			item.readOnly = true
		})
		this.salesArea = arrArea
		this.companyProp.map(item => {
			if (item.checked) {
				arrCompany.push(item)
			}
			item.readOnly = true
		})
		this.companyProp = arrCompany
		this.setState({ ls: true })
	}
	_RadoiCallBack = (data) => {
		this.setState({
			channel: data.channel
		}, () => {
			console.log(this.state.channel)
		})
	}
	//回调
	_baseCallBack = (data) => {
		this.typeParams = Object.assign({}, this.typeParams, data);
		this.setState({
			ls: true
		})
	}
	_select = (checked, index) => {
		let { dataList, readOnly } = this.state
		if (readOnly) {
			return
		}
		dataList[index].checked = !checked
		this.groupParams.resourceGroupIds = []
		dataList.map(item => {
			if (item.checked) {
				this.groupParams.resourceGroupIds.push(item.resourceGroupId)
			}
		})
		this.setState({
			dataList
		})
	}
	_renderFilterWrap() {
		return (
			<View style={styles.filterWrap}>
				<View>
					<Image source={searchIcon} style={styles.searchIcon} />
					<TextInput
						ref="enterpriseInput"
						style={styles.searchInput}
						underlineColorAndroid='transparent'
						placeholder={"请输入群组名称"}
						placeholderTextColor="rgba(255, 255, 255, .8)"
						maxLength={30}
						returnKeyType={'search'}
						defaultValue={this.searchKey}
						onChangeText={(txt) => { this.searchKey = txt; }}
						onSubmitEditing={() => { this.initPage(); }}
					/>
				</View>
			</View>
		)
	}

	callBackfuc = (data) => {
		let { callback } = this.props.navigation.state.params
		callback(data)
		this.props.navigation.goBack()
	}
	conform = () => {
		let { channel } = this.state;
		let { areaIds, companyTypes } = this.typeParams
		let { resourceGroupIds } = this.groupParams
		if (channel === '1') {
			if (resourceGroupIds.length == 0) {
				Alert.alert('请选择定向群组客户')
				return
			}
			this.callBackfuc({
				channel, areaIds: [], companyTypes: [], resourceGroupIds
			})
		}
		else {
			if (areaIds.length == 0) {
				Alert.alert('请选择客户区域客户')
				return
			}
			else if (companyTypes.length == 0) {
				Alert.alert('请选择企业性质客户')
				return
			}
			this.callBackfuc({
				channel, areaIds, companyTypeIds: companyTypes, resourceGroupIds: []
			})
		}
	}
	render() {
		let { channel, dataList, status, readOnly } = this.state;
		let { areaIds, companyTypes } = this.typeParams
		let { resourceGroupIds } = this.groupParams;
		return (
			<View style={styles.container}>
				<View>
					{channel === '1' && !readOnly ? this._renderFilterWrap() : null}
					<View style={styles.box}>
						<RadoiCpt data={{
							id: 'channel',
							selectKey: channel,
							title: '企业渠道',
							listData: this.EnterpriseChannel,
							required: true
						}}
							callBack={this._RadoiCallBack}
						/>
						{channel === '1' ?
							<View>
								<View style={styles.selectTitle}>
									<View>
										<Text style={styles.required}>* </Text>
										<Text style={{ fontSize: 14 * scale, color: '#000' }}>选择定向群组客户</Text>
									</View>
									<TouchableOpacity onPress={() => {
										if (resourceGroupIds.length > 0) {
											this.props.navigation.navigate('OfferEnterpriseList', this.groupParams)
										}
										else {
											Alert.alert('请选择定向群组客户')
										}
									}}>
										<Text style={{ fontSize: 14 * scale, color: style.color.themeColor }}>【查看推送企业】</Text>
									</TouchableOpacity>
								</View>
							</View>
							: null
						}
					</View>
				</View>
				{channel === '1' ?
					<ScrollView style={{
						marginHorizontal: 20 * scale,
						// paddingVertical: 10 * scale
					}}>
						{status == 'data' ?
							<View>
								{dataList && dataList.map((item, index) => {
									return (
										<TouchableOpacity style={styles.clickButtom} onPress={() => { this._select(item.checked, index) }} key={index}>
											<Image source={item.checked ? checkOff : checkOn} style={[styles.checkBoxImg, readOnly ? { tintColor: '#999999' } : null]} />
											<Text>{item.resourceGroupName}</Text>
										</TouchableOpacity>
									)
								})}
							</View> :
							<PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this.initPage} />
						}
					</ScrollView> : null
				}
				{channel === '2' ?
					<View style={{ flex: 1, marginHorizontal: 20 * scale, }}>
						<CheckBoxCpt
							data={{
								id: 'areaIds',
								title: '客户区域',
								listData: this.salesArea,
								selectKeyArr: areaIds || [],
								required: true
							}}
							callBack={this._baseCallBack}
						/>
						<CheckBoxCpt
							data={{
								id: 'companyTypes',
								title: '企业性质',
								listData: this.companyProp,
								selectKeyArr: companyTypes || [],
								required: true
							}}
							callBack={this._baseCallBack}
						/>
						<TouchableOpacity style={styles.clickButtom} onPress={() => {
							if (!areaIds || areaIds.length == 0) {
								Alert.alert('请选择客户区域')
							}
							else if (!companyTypes || companyTypes.length == 0) {
								Alert.alert('请选择企业性质')
							}
							else {
								this.props.navigation.navigate('OfferEnterpriseList', this.typeParams)
							}
						}}>
							<View>
								<Text>查看推送企业信息</Text>
							</View>
						</TouchableOpacity>
					</View> : null
				}
				{!readOnly ?
					<View style={styles.btnBoxBig}>
						<View style={styles.btnBox}>
							<TouchableOpacity style={styles.BtnBg} onPress={() => {
								this.conform()
							}}>
								<Text style={styles.BtnText}>确认</Text>
							</TouchableOpacity>
						</View>
					</View>
					: null
				}
			</View>
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#E8ECF5',
	},
	box: {
		marginHorizontal: 20 * scale,
		paddingTop: 10 * scale
	},
	btnBoxBig: {
		width: 375 * scale,
		height: 80 * scale,
		backgroundColor: '#E8ECF5',
	},
	btnBox: {
		flexDirection: 'row',
		justifyContent: 'center',
		marginVertical: 20 * scale,
	},
	BtnBg: {
		backgroundColor: style.color.themeColor,
		paddingHorizontal: 25 * scale,
		//paddingVertical: 10 * scale,
		height: 32 * scale,
		borderRadius: 15 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
	},
	BtnText: {
		fontSize: 13 * scale,
		color: style.color.white
	},
	BtnBgR: {
		marginLeft: 30 * scale
	},
	textArea: {
		height: 64 * scale,
		backgroundColor: '#fff',
		marginTop: 10 * scale,
		borderRadius: 8 * scale,
		paddingHorizontal: 15 * scale,
		paddingVertical: 35 * scale,
		paddingVertical: 0,
		borderWidth: 0,
		marginBottom: 20 * scale
	},
	clickButtom: {
		backgroundColor: '#fff',
		borderRadius: 5 * scale,
		paddingHorizontal: 10 * scale,
		paddingVertical: 12 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		marginBottom: 10 * scale
	},
	checkBoxImg: {
		width: 13 * scale,
		height: 13 * scale,
		marginRight: 6 * scale,
		tintColor: '#0087FF',
	},
	selectTitle: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		marginBottom: 20 * scale
	},
	required: {
		position: 'absolute',
		top: 2 * scale,
		left: -8 * scale,
		color: 'red'
	},
	filterWrap: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor: style.color.themeColor,
		paddingTop: 14 * scale,
		paddingBottom: 14 * scale,
	},
	searchInput: {
		height: 36 * scale,
		width: 270 * scale,
		paddingLeft: 90 * scale,
		paddingRight: 12 * scale,
		backgroundColor: 'rgba(255, 255, 255, .18)',
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingVertical: 0,
		position: 'relative',
		borderRadius: 8 * scale,
		color: '#fff',
	},
	searchIcon: {
		width: 20 * scale,
		height: 22 * scale,
		position: 'absolute',
		left: 40 * scale,
		top: 8 * scale,
		zIndex: 9,
		opacity: 0.8,
	},
})